package rpc.units;

import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

public class SocketUnits {

    private static final int MAXBYTELENGTH=65536;//10KB
    private static final int SINGLELENGTH=1024;//单次发送一KB数据
    private static final int PRELENGTHHEAD=4;//数据报长度:'1024'最多占4字节

    //发送消息,JSON格式字符串
    @SneakyThrows
    public static void sendMsg(Socket socket, String msg) throws RuntimeException, IOException {

        byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
        if(bytes.length>MAXBYTELENGTH){
            throw new RuntimeException("发送的消息体过长"+bytes.length+",长度应该在"+MAXBYTELENGTH+"以下");
        }
        String msgLength= StringUtils.leftPad(String.valueOf(bytes.length),5,"0");
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(msgLength.getBytes(StandardCharsets.UTF_8));//先写入长度
        if(bytes.length<SINGLELENGTH){
            //直接单次发送完即可
            outputStream.write(bytes);
            outputStream.flush();
            return;
        }
        //需要多次发送
        byte[] singleBytes=new byte[SINGLELENGTH];
        int count= (int) Math.ceil((double) bytes.length/singleBytes.length);
        int startIndex=0;
        while (count > 0) {
            if(count==1){
                singleBytes=new byte[SINGLELENGTH];
                System.arraycopy(bytes,startIndex,singleBytes,0,bytes.length-startIndex);
                outputStream.write(singleBytes);
                break;
            }
            System.arraycopy(bytes,startIndex,singleBytes,0,SINGLELENGTH);
            startIndex+=SINGLELENGTH;
            outputStream.write(singleBytes);//写入后立马发送
            System.out.println("发送:"+System.currentTimeMillis());
            Thread.sleep(1000);
            count--;
        }
        outputStream.flush();//缓冲区未满也直接发送
    }

    //接收消息
    public static String receiveMsg(Socket socket) throws IOException {

        InputStream inputStream = socket.getInputStream();
        byte[] lengthBytes=new byte[5];
        inputStream.read(lengthBytes,0,5);
        Integer length = Integer.parseInt(new String(lengthBytes, StandardCharsets.UTF_8));
        byte[] bytes=new byte[length];
        int count=0;
        int available = 1024;
        while (available==1024){
            available=inputStream.read(bytes,count*SINGLELENGTH,Math.min(SINGLELENGTH,length-(count*SINGLELENGTH)));
            System.out.println("接收:"+System.currentTimeMillis());
            count++;
        }

        String result = new String(bytes, StandardCharsets.UTF_8);
        return result;
    }

    public static void main(String[] args) {
        System.out.println(Integer.MAX_VALUE);
    }

}
